import React, { useCallback, useEffect, useState } from 'react';
import request from '@/utils/request';

function flattenTree(data) {
  return data.reduce((acc, item) => {
    acc.push(item);
    if (item.children) {
      acc.push(...flattenTree(item.children));
    }
    return acc;
  }, []);
}

function useProcessCatalogTreeData(withLeaves = false) {
  const [data, setData] = useState([]);
  const [flattenData, setFlattenData] = useState([]);
  const [loading, setLoading] = useState(false);

  // 刷新树
  const refresh = useCallback(() => {
    setLoading(true);
    request
      .get(`/process/listCatalogTree?withLeaves=${withLeaves}`)
      .then(data => {
        setData(data);
        setFlattenData(flattenTree(data));
      })
      .finally(() => setLoading(false));
  }, [withLeaves]);

  useEffect(() => {
    refresh();
  }, [refresh]);

  return { data, loading, refresh, flattenData };
}

export default useProcessCatalogTreeData;
